<template>
	<div class="loginflexcolumn" id="allscreen" v-show="!autoCallPage">
		<form class="loginflexcolumn">
			<!-- <div class="language" @click="changeLanguage()">
				<div class="langtxt">{{ nowLanguage }}</div>
				<img src="../../static/image/downn.png" class="downimg" />
			</div> -->
			<!-- <img src="../../static/image/logo.png" class="logo" /> -->
			<div class="logo"></div>
			<div class="title">{{ $t('ivcs.systemtitle') }}</div>
			<div class="row" style="margin-top: 50px">
				<img src="../../static/image/user.png" class="smallimg" />
				<input :placeholder="nameplacehold" class="input" v-model="userId" @keyup.enter="customerLogin" />
			</div>
			<div class="line"></div>

			<div class="row" style="margin-top: 20px">
				<img src="../../static/image/org.png" class="smallimg" />
				<input :placeholder="orgplacehold" class="input" id="org" v-model="org" @keyup.enter="customerLogin" />
			</div>
			<div class="line"></div>

			<!-- <div class="op">
				<div v-show="!rempwd" @click="setrempwd" class="norempwdimg"></div>
				<img src="../../static/image/rempwd.png" class="rempwdimg" @click="setrempwd" v-show="rempwd" />
				<div class="rempwdtext" @click="setrempwd">{{ $t('ivcs.rempwd') }}</div>
			</div> -->
			<div class="loginbtn" :class="userId && org ? 'defaultbackColor' : 'gray'" @click="customerLogin">{{ $t('ivcs.login') }}</div>
		</form>
		<div class="coverlayer" v-show="isShowSafariGuide">
			<div class="textImg">
				<img src="../../static/image/login/text.png" alt="" />
			</div>
			<div class="guideImg">
				<img src="../../static/image/login/guideline.png" alt="" />
			</div>
		</div>
		<!-- <RemoteLink v-if="showRemotelink" ref="remoteLink"></RemoteLink> -->
	</div>
</template>

<script>
import uneyes from '../../static/image/uneyes.png';

import eyes from '../../static/image/eyes.png';

import { refreshToken, visitorLogin, getCallCode } from '../api/api';

import jwt from 'jsonwebtoken';

import { ZBase64 } from '../tool/util';

import Language from '../components/Language';
import { mapMutations } from 'vuex';

export default {
	name: 'Login',
	data() {
		return {
			name: null,
			userId: null,
			pwd: null,
			org: null,
			eyesimage: uneyes,
			rempwd: true,
			nowLanguage: localStorage.getItem('language'),
			serviceId: null,
			isShowSafariGuide: false,
			showRemotelink: true,
			inviteCode: '',
			autoCallPage: false // 	自动呼叫
		};
	},
	component: {
		Language
	},

	components: {},

	computed: {
		nameplacehold() {
			if (this.userId) {
				return '';
			}
			return '请输入访客ID';
			// this.$t('ivcs.plname');
		},

		pwdplacehold() {
			if (this.pwd) {
				return '';
			}
			return this.$t('ivcs.plpwd');
		},

		orgplacehold() {
			if (this.org) {
				return '';
			}
			return this.$t('ivcs.plorg');
		}
	},

	mounted() {
		// console.log('ivcsCustomer', ivcsCustomer);
		this.checkPlatform();
		let browserSupport = navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
		let webRTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection || window.RTCIceGatherer;
		if (!browserSupport || !webRTCPeerConnection) {
			alert(this.$t('ivcs.support'));
			this.$Notice.warning({
				title: this.$t('ivcs.confirm'),
				desc: this.$t('ivcs.support'),
				duration: 10,
				top: 0
			});
		}
		if (localStorage.getItem('pwd')) {
			var base = new ZBase64();
			this.name = localStorage.getItem('name');
			this.pwd = base.decode(localStorage.getItem('pwd'));
			this.org = localStorage.getItem('org');
		}
		console.log(this.$route.query);
		if (this.refreshTokenInterval) {
			clearInterval(this.refreshTokenInterval);
		}
		let query = this.$route.query;
		if (query.name && query.pwd && query.org) {
			this.name = query.name;
			this.pwd = query.pwd;
			this.org = query.org;
			this.serviceId = query.serviceId;
			this.customerLogin();
		}
		this.inviteCode = query.inviteCode;
		this.org = query.org ? query.org : localStorage.getItem('org');
		if (this.inviteCode) {
			this.$router.push('/start?inviteCode=' + this.inviteCode + '&org=' + this.org);
		}

		// 自动呼叫
		if (query.autoCall) {
			this.autoCallPage = true;
			this.autoCall(query.org, query.agentId, query.bizscenariosId);
			localStorage.setItem('org', query.org ? query.org : org);
		}
	},

	beforeRouteEnter(to, from, next) {
		// 在渲染该组件的对应路由被 confirm 前调用
		// 不！能！获取组件实例 `this`
		// 因为当守卫执行前，组件实例还没被创建
		next();
	},
	beforeRouteUpdate(to, from, next) {
		// 在当前路由改变，但是该组件被复用时调用
		// 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候，
		// 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
		// 可以访问组件实例 `this`
		next();
	},
	beforeRouteLeave(to, from, next) {
		// 导航离开该组件的对应路由时调用
		// 可以访问组件实例 `this`
		console.log(from);
		if (from.name === 'login' && to.name === 'videosession' && !from.fullPath.includes('callcode')) {
			//用户从聊天页面误操作 返回上一个页面了
			this.$Message.error('The login page does not support return operations!');
			next(false); //work
		} else {
			next();
		}
	},

	methods: {
		...mapMutations('user', ['SET_CUSTOMER_INFO']),
		...mapMutations('initUserData', ['SET_CLIENT_DATA']),
		checkPlatform() {
			var ua = navigator.userAgent.toLowerCase();
			var isWeixin = ua.indexOf('micromessenger') != -1;
			if (isWeixin && /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
				var test = /os\s([\w_]+)/;
				var match = test.exec(ua);
				var version = match[1].split('_')[0];
				var edition = match[1].split('_')[1];
				var paper = version + '.' + edition;
				if (paper < 14.3) {
					this.isShowSafariGuide = true;
				} else {
					this.isShowSafariGuide = false;
				}
			} else {
				this.isShowSafariGuide = false;
			}
		},

		changeLanguage() {
			var self = this;
			this.$Modal.success({
				title: '',
				render: h => {
					return h(Language, {
						ref: 'Language'
					});
				},
				width: 600,
				closable: false,
				okText: 'OK',
				onOk() {
					console.log(this.$refs.Language.language);
					if (this.$refs.Language.language === '简体中文') {
						localStorage.setItem('language', '简体中文');
						localStorage.setItem('lang', 'zh');
						self.$i18n.locale = 'zh';
						self.nowLanguage = localStorage.getItem('language');
					} else if (this.$refs.Language.language === '繁体中文') {
						localStorage.setItem('language', '繁体中文');
						localStorage.setItem('lang', 'tw');
						self.$i18n.locale = 'tw';
						self.nowLanguage = localStorage.getItem('language');
					}
				},
				onCancel() {}
			});
		},

		setrempwd() {
			this.rempwd = !this.rempwd;
		},

		gotoregister() {
			this.$router.push('/register');
		},

		/**
		 * 自动呼叫
		 * @param {*} org
		 * @param {*} agentId
		 * @param {*} bizId
		 */
		autoCall(callorg, agentId, bizId) {
			let query = this.$route.query;
			console.log('query', query);
			this.$Spin.show();
			let parameter = {
				bizScenId: bizId ? bizId : bizscenariosId,
				type: 1,
				org: callorg ? callorg : org,
				agentId: agentId ? agentId : '',
				startDate: '',
				endDate: '',
				customerId: '',
				customerRole: '访客'
			};
			getCallCode(parameter)
				.then(resp => {
					console.log('callcdoe', resp);
					if (resp && resp.data) {
						const callCode = resp.data;
						console.log('query.screenSync', query.screenSync);
						let screenSync = query.screenSync ? '&screenSync=' + query.screenSync : '';
						let callType = query.callType ? '&callType=' + query.callType : '';
						let receiveType = query.receiveType ? '&receiveType=' + query.receiveType : '';
						// https://localhost:8082/?autoCall=1&agentId=001&org=sun&bizscenariosId=255&screenSync=1&callType=audio&receiveType=audio
						this.$router.push('/start?callCode=' + callCode + screenSync + callType + receiveType);
					} else {
						this.$Message.error('请求异常，请稍后重试！');
					}
					this.$Spin.hide();
				})
				.catch(error => {
					console.log(error);
					this.$Spin.hide();
					this.$Message.error('服务异常，请稍后重试！');
				});
		},

		/**
		 * 访客初始化登录
		 */
		customerLogin() {
			if (this.userId == null || this.userId === '') {
				this.$Message.info('请输入访客ID');
				return;
			} else if (this.org == null || this.org === '') {
				this.$Message.info(this.$t('ivcs.plorg'));
				return;
			}
			localStorage.setItem('userId', this.userId.trim());
			localStorage.setItem('org', this.org.trim());
			localStorage.setItem('name', this.userId.trim());
			this.$Spin.show();
			visitorLogin({ id: this.userId.trim(), org: this.org.trim() })
				.then(res => {
					console.log(res, 'login success', this.pwd);
					if (res.status === 200) {
						this.setUserInfo(res.data.data);
						this.setNext();
						this.$Spin.hide();
					}
				})
				.catch(error => {
					console.log(error, 'login error');
					this.$Spin.hide();
					if (error && error.data && error.data.code === '1103') {
						this.$Message.error(this.$t('login.pwdError'));
					} else if (error && error.data && error.data.code === '1001') {
						this.$Message.error(this.$t('login.userNotExist'));
					} else if (error && error.data && error.data.code === '1104') {
						this.$Message.error(this.$t('login.accountInvalid'));
					} else if (error && error.data && error.data.code == 1301) {
						if (error && error.data && error.data.data.errorCode === '4') {
							this.$Message.error('填写的机构名称不存在');
						}
					} else {
						this.$Message.error(this.$t('login.serviceException'));
					}
				});
		},

		/**
		 * 存储用户信息
		 */
		setUserInfo(response) {
			let result = jwt.decode(response.accessToken ? response.accessToken : response.token);
			console.log('login result', result);
			let refreshTicketTimeMs = result.exp - result.iat - 1 > 0 ? (result.exp - result.iat - 1) * 1000 : 1000;
			let userId = result.data ? result.data.id : '';
			let ticket = response.ticket;
			localStorage.setItem('customer_token', response.accessToken ? response.accessToken : response.token);
			localStorage.setItem('customer_ticket', ticket);
			localStorage.setItem('org', result.data.org);
			this.autoRefreshToken(userId, refreshTicketTimeMs);
			let userPicture = result.data && result.data.profile && result.data.profile.picture ? result.data.profile.picture : '';
			localStorage.setItem('userPicture', userPicture);

			let fullName = result.data && result.data.profile && result.data.profile.fullName ? result.data.profile.fullName : '';
			localStorage.setItem('fullName', fullName);

			let gender = result.data && result.data.profile && result.data.profile.gender ? (result.data.profile.gender == 'male' ? '先生' : '女士') : '';
			localStorage.setItem('gender', gender);
			var urls = response.urls;
			localStorage.setItem('serverUrl', urls.backendurl);
			localStorage.setItem('ccsUrl', urls.ccsurl);
			localStorage.setItem('turnserverUrl', urls.turnserverUrl);
			localStorage.setItem('turnserverCredential', urls.turnserverCredential);
			localStorage.setItem('turnserverUsername', urls.turnserverUsername);
			let user = {};
			user.id = userId;
			user.avatar = userPicture;
			user.fullName = fullName;
			user.customerLevel = result.data.customerLevel;
			user.org = result.data.org;
			user.role = result.data.role;
			user.userName = result.data.userName;
			user.gender = gender;
			this.$store.commit('SET_CUSTOMER_INFO', user);
		},

		setNext() {
			let query = this.$route.query;
			let virtualAgentType = query.virtualAgentType;
			let qv = '';
			if (virtualAgentType) {
				if (virtualAgentType !== 'registered' && virtualAgentType !== 'unregistered') {
					virtualAgentType = 'registered';
				}
				qv = 'virtualAgentType=' + virtualAgentType;
			}
			if (this.inviteCode) {
				this.$router.push('/start?inviteCode=' + this.inviteCode + '&' + qv);
				// sessionStorage.setItem('service', this.inviteCode);
				sessionStorage.setItem('inviteCode', this.inviteCode);
			} else {
				this.$router.push('/servertype' + '?' + qv);
			}
		},

		autoRefreshToken(userId, intervalMs) {
			this.refreshTokenInterval = setInterval(() => {
				let para = {
					userId: userId,
					ticket: localStorage.getItem('customer_ticket')
				};
				refreshToken(para).then(resp => {
					console.log('refresh token', resp, new Date());
					localStorage.setItem('customer_token', resp.data.accessToken);
					localStorage.setItem('customer_ticket', resp.data.ticket);
				});
			}, intervalMs);
		},

		requestError(response) {
			if (response && response.data) {
				var code = response.data.code;
				if (code === '1302') {
					this.$Message.error(this.$t('login.pwdSame'));
				} else if (code === '1001') {
					//用户不存在
					this.$Message.error(this.$t('login.userNotExist'));
				} else if (code === '1002') {
					this.$Message.error(this.$t('login.userExist'));
				} else if (code === '1103') {
					//密码错误
					this.$Message.error(this.$t('login.pwdError'));
				} else if (code === '1104') {
					this.$Message.error(this.$t('login.accountError'));
				} else if (code === '1401') {
					this.$Message.error(this.$t('login.dbError'));
				} else if (code === '1301') {
					this.$Message.error(this.$t('login.sendDataError'));
				} else if (code === '1101') {
					this.$Message.error(this.$t('login.accountAuthError'));
				} else if (code === '1102') {
					this.$Message.error(this.$t('login.requestReject'));
				} else if (response.status === 401) {
					this.$Message.error(this.$t('login.accountInvalid'));
				}
			}
		},

		rememberInfo() {
			var base = new ZBase64();
			localStorage.setItem('pwd', base.encode(this.pwd));
		},

		showpwd() {
			let password = document.getElementById('password');
			if (password.type === 'password') {
				password.type = 'text';
				this.eyesimage = eyes;
			} else {
				password.type = 'password';
				this.eyesimage = uneyes;
			}
		}
	}
};
</script>

<style scoped>
.coverlayer {
	position: absolute;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.8);
	filter: alpha(opacity=60);
	z-index: 999;
}
.textImg {
	position: absolute;
	top: 140px;
	left: 35px;
}
.guideImg {
	position: absolute;
	top: 20px;
	right: 20px;
}
.loginflexcolumn {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	width: 100%;
	left: 0px;
	top: 0px;
}

.line {
	height: 1px;
	background: rgba(217, 217, 217, 1);
	width: 80%;
	margin-top: 10px;
}

.op {
	height: 40px;
	/*background:red;*/
	width: 80%;
	margin-top: 8px;
	display: flex;
	flex-direction: row;
	justify-content: flex-start;
	align-items: center;
}

.register {
	/*width:55px;*/
	height: 40px;
	font-size: 14px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: rgba(100, 202, 171, 1);
	line-height: 40px;
	text-align: right;
	align-self: flex-end;
	flex: 1;
}

.loginbtn {
	width: 80%;
	height: 40px;
	border-radius: 20px;
	line-height: 40px;
	font-size: 16px;
	font-family: PingFangSC-Semibold, PingFangSC;
	color: rgba(255, 255, 255, 1);
	margin-top: 100px;
}

.logo {
	margin-top: 25%;
	width: 120px;
	height: 24px;
}

.rempwdimg {
	width: 12px;
	height: 12px;
}

.norempwdimg {
	width: 12px;
	height: 12px;
	border-radius: 2px;
	border: 1px solid rgba(100, 202, 171, 1);
}

.rempwdtext {
	display: inline-block;
	box-sizing: border-box;
	vertical-align: middle;
	height: 100%;
	width: 100px;
	text-align: left;
	line-height: 40px;
	margin-left: 5px;
	font-size: 13px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: rgba(100, 202, 171, 1);
}

.title {
	width: 80%;
	height: 33px;
	font-size: 12px;
	font-family: PingFangSC-Regular, PingFangSC;
	font-weight: 400;
	color: rgba(167, 167, 167, 1);
	line-height: 33px;
	margin-top: 0px;
}

.input {
	width: 65%;
	height: 30px;
	border: 0px;
	margin-left: 10px;
}

input,
input:active {
	border: none !important;
	/*border-bottom: 1px solid #d2d2d2 !important;*/
	outline: none;
	box-shadow: none;
}

.smallimg {
	width: 20px;
	height: 22px;
	margin-left: 10%;
}

.eyesimage {
	width: 22px;
	height: 22px;
}

.row {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: flex-start;
	width: 100%;
	left: 20%;
}

.language {
	position: absolute;
	top: 30px;
	right: 10px;
	width: 200px;
	height: 40px;
	/*background-color: yellow;*/
	display: flex;
	flex-direction: row;
	justify-content: flex-end;
	align-items: center;
}

.langtxt {
	width: 95px;
	height: 40px;
	font-size: 13px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: rgba(100, 202, 171, 1);
	line-height: 40px;
	text-align: right;
	margin-right: 3px;
}

.downimg {
	width: 10px;
	height: 8px;
}

.gray {
	background: rgba(217, 217, 217, 1);
}
</style>
